<?php

namespace app\admin\controller\manufacture;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 生产计划管理
 *
 * @icon fa fa-calendar
 * @remark 管理生产计划，与订单系统集成
 */
class Plan extends Backend
{
    /**
     * Plan模型对象
     * @var \app\admin\model\manufacture\Plan
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\manufacture\Plan;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("priorityList", $this->model->getPriorityList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['order'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        // 获取订单列表
        $orderList = \app\admin\model\scanwork\Order::where('status', 'in', [0, 1])
            ->field('id, order_no, customer_name, total_quantity')
            ->select();
        $this->view->assign('orderList', $orderList);
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                // 生成计划编号
                $params['plan_no'] = $this->generatePlanNo();
                $params['creator_id'] = $this->auth->id;
                
                // 获取订单信息
                $order = \app\admin\model\scanwork\Order::find($params['order_id']);
                if ($order) {
                    $params['order_no'] = $order->order_no;
                    $params['customer_name'] = $order->customer_name;
                    $params['planned_quantity'] = $order->total_quantity;
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    
                    $result = $this->model->allowField(true)->save($params);
                    
                    // 创建计划明细
                    if ($result && $order) {
                        $this->createPlanDetails($this->model->id, $order->id);
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取订单列表
        $orderList = \app\admin\model\scanwork\Order::where('status', 'in', [0, 1])
            ->field('id, order_no, customer_name, total_quantity')
            ->select();
        $this->view->assign('orderList', $orderList);
        
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    // 删除计划明细
                    \app\admin\model\manufacture\PlanDetail::where('plan_id', $item->id)->delete();
                    $count += $item->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }

    /**
     * 查看详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取计划明细
        $planDetails = \app\admin\model\manufacture\PlanDetail::with(['model.product', 'process'])
            ->where('plan_id', $ids)
            ->select();
        
        $this->view->assign('row', $row);
        $this->view->assign('planDetails', $planDetails);
        
        return $this->view->fetch();
    }

    /**
     * 发布计划
     */
    public function publish($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('计划不存在');
        }
        
        if ($row->status != 0) {
            $this->error('只能发布草稿状态的计划');
        }
        
        $row->status = 1; // 已发布
        $row->save();
        
        $this->success('计划发布成功');
    }

    /**
     * 开始执行
     */
    public function start($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('计划不存在');
        }
        
        if ($row->status != 1) {
            $this->error('只能执行已发布状态的计划');
        }
        
        $row->status = 2; // 执行中
        $row->save();
        
        $this->success('计划开始执行');
    }

    /**
     * 完成计划
     */
    public function complete($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('计划不存在');
        }
        
        if ($row->status != 2) {
            $this->error('只能完成执行中状态的计划');
        }
        
        $row->status = 3; // 已完成
        $row->save();
        
        $this->success('计划已完成');
    }

    /**
     * 生成计划编号
     */
    private function generatePlanNo()
    {
        $prefix = 'PLAN';
        $date = date('Ymd');
        $random = strtoupper(substr(md5(uniqid()), 0, 6));
        return $prefix . $date . $random;
    }

    /**
     * 创建计划明细
     */
    private function createPlanDetails($planId, $orderId)
    {
        // 获取订单型号
        $orderModels = \app\admin\model\scanwork\OrderModel::where('order_id', $orderId)->select();
        
        // 获取工序列表
        $processes = \app\admin\model\scanwork\Process::where('status', 1)->order('sequence')->select();
        
        foreach ($orderModels as $orderModel) {
            foreach ($processes as $process) {
                \app\admin\model\manufacture\PlanDetail::create([
                    'plan_id' => $planId,
                    'model_id' => $orderModel->model_id,
                    'process_id' => $process->id,
                    'planned_quantity' => $orderModel->quantity,
                    'sequence' => $process->sequence,
                    'status' => 0,
                    'createtime' => time()
                ]);
            }
        }
    }

    /**
     * 查看工序进度
     */
    public function process($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取计划明细
        $planDetails = \app\admin\model\manufacture\PlanDetail::with(['productModel.product', 'process'])
            ->where('plan_id', $ids)
            ->order('sequence')
            ->select();
        
        // 获取报工记录
        $workRecords = \app\admin\model\scanwork\WorkRecord::alias('wr')
            ->join('scanwork_order o', 'wr.order_id = o.id')
            ->join('scanwork_process p', 'wr.process_id = p.id')
            ->where('o.id', $row->order_id)
            ->field('wr.*, p.name as process_name, p.sequence')
            ->order('p.sequence, wr.createtime desc')
            ->select();
        
        // 计算进度
        $progress = $this->calculateProgress($row->order_id);
        
        $this->view->assign('row', $row);
        $this->view->assign('planDetails', $planDetails);
        $this->view->assign('workRecords', $workRecords);
        $this->view->assign('progress', $progress);
        
        return $this->view->fetch();
    }

    /**
     * 获取订单进度数据
     */
    public function getOrderProgress()
    {
        $orderId = $this->request->get('order_id');
        if (!$orderId) {
            $this->error('订单ID不能为空');
        }
        
        $progress = $this->calculateProgress($orderId);
        return json($progress);
    }

    /**
     * 计算订单进度
     */
    private function calculateProgress($orderId)
    {
        // 获取订单信息
        $order = \app\admin\model\scanwork\Order::find($orderId);
        if (!$order) {
            return [];
        }
        
        // 获取工序列表
        $processes = \app\admin\model\scanwork\Process::order('sequence')->select();
        
        // 获取报工记录
        $workRecords = \app\admin\model\scanwork\WorkRecord::where('order_id', $orderId)
            ->field('process_id, SUM(quantity) as completed_quantity')
            ->group('process_id')
            ->select();
        
        $workRecordMap = [];
        foreach ($workRecords as $record) {
            $workRecordMap[$record->process_id] = $record->completed_quantity;
        }
        
        // 计算每个工序的进度
        $progress = [];
        $totalProgress = 0;
        
        foreach ($processes as $process) {
            $completedQuantity = isset($workRecordMap[$process->id]) ? $workRecordMap[$process->id] : 0;
            $progressRate = $order->total_quantity > 0 ? round(($completedQuantity / $order->total_quantity) * 100, 2) : 0;
            
            $progress[] = [
                'process_id' => $process->id,
                'process_name' => $process->name,
                'sequence' => $process->sequence,
                'total_quantity' => $order->total_quantity,
                'completed_quantity' => $completedQuantity,
                'progress_rate' => $progressRate,
                'status' => $completedQuantity >= $order->total_quantity ? 'completed' : ($completedQuantity > 0 ? 'in_progress' : 'pending')
            ];
            
            $totalProgress += $progressRate;
        }
        
        // 计算总体进度
        $overallProgress = count($processes) > 0 ? round($totalProgress / count($processes), 2) : 0;
        
        return [
            'order_id' => $orderId,
            'order_no' => $order->order_no,
            'customer_name' => $order->customer_name,
            'total_quantity' => $order->total_quantity,
            'overall_progress' => $overallProgress,
            'processes' => $progress
        ];
    }
}
